package com.user.gamecenter.manager;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.limpoxe.fairy.content.PluginDescriptor;
import com.limpoxe.fairy.manager.PluginManagerHelper;
import com.user.gamecenter.app.MyApp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

/**
 * author : Administrator
 * e-mail : 254419013@qq.com
 * time   : 2017/06/28
 * desc   :
 */
public class PlugInManager {

    private static final String TAG = "PlugInManager";

    public static int install(String pluginPath) {
        int install = PluginManagerHelper.installPlugin(pluginPath);
        Log.d(TAG, "install:" + install);
        return install;
    }

    public static void removePlugIn() {
        PluginManagerHelper.remove(MyApp.plugInPackageName);
    }

    public static boolean isPlugin() {
        boolean isPlugin = false;

        ArrayList<PluginDescriptor> pluginDescriptorArrayList = PluginManagerHelper.getPlugins();
        for (PluginDescriptor pluginDescriptor : pluginDescriptorArrayList) {
            if (MyApp.plugInPackageName.equals(pluginDescriptor.getPackageName())) {
                isPlugin = true;
                break;
            }
        }
        Log.d("PlugInManager", "isPlugin:" + isPlugin);
        return isPlugin;
    }

    public static void initInstall(Context context, String fileName, String path) {
        if (copyApkFromAssets(context, fileName, path)) {
            install(MyApp.plugInPath);
        }
    }


    /**
     * @方法名：
     * @author : Administrator
     * @e-mail : 254419013@qq.com
     * @time : 2017/6/30 11:11
     * @desc : 获取当前插件的版本号
     */
    public static int getPlugInVersion(Context context, String filePath) {
        File file = new File(filePath);
        int version = 0;
        if (file.exists()) {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageArchiveInfo(filePath, PackageManager.GET_ACTIVITIES);
            version = packageInfo.versionCode;
        }
        return version;
    }


    private static boolean copyApkFromAssets(Context context, String fileName, String path) {
        boolean copyIsFinish = false;
        try {
            InputStream is = context.getAssets().open(fileName);
            File file = new File(path);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] temp = new byte[1024];
            int i = 0;
            while ((i = is.read(temp)) > 0) {
                fos.write(temp, 0, i);
            }
            fos.close();
            is.close();
            copyIsFinish = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return copyIsFinish;
    }
}
